<template>
    <div id="add-edit-model">
        <el-dialog
            :title="titleCon"
            v-model="isUseDialog" 
            draggable 
            :close-on-click-modal="false" 
            width="60%" 
            :before-close="handleClose"
            :destroy-on-close="true"
            @close="clean"
        >
            <el-form :model="ruleForm" ref="ruleFormRef" size="default" label-width="140px" :rules="rules">
                <el-row :gutter="35">
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="培训计划" prop="v_CourseName">
                            <el-select
                                filterable
                                v-model="ruleForm.v_CourseName" 
                                placeholder="请选择培训计划" 
                                value-key='id'
                                @change="planChange"
                            >
                                <el-option
                                    v-for="item in planOption"
                                    :key="item.id"
                                    :label="item.v_CourseName"
                                    :value="item"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="考卷名称" prop="v_Name">
                            <el-input v-model="ruleForm.v_Name" placeholder="请输入考卷名称" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="考试时长(分钟)" prop="n_Min">
                            <el-input type="number" v-model="ruleForm.n_Min" placeholder="请输入考试时长(分钟)" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="奖惩措施">
                            <el-input v-model="ruleForm.v_PIDM" placeholder="请输入奖惩措施" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="选题方式">
                            <el-select 
                                v-model="ruleForm.n_SelectionMethod" 
                                placeholder="请选择选题方式" 
                                @change="selectTopicChange"
                            >
                                <el-option
                                    v-for="item in selectTopicOption"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="优秀线(分数)" prop="n_ScopeExcellentMin">
                            <el-input v-model="ruleForm.n_ScopeExcellentMin" type="number" placeholder="请输入优秀线" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="合格线(分数)" prop="n_ScopeQualifiedMin">
                            <el-input v-model="ruleForm.n_ScopeQualifiedMin" type="number" placeholder="请输入合格线" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col v-if="ruleForm.n_SelectionMethod === 0" :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="题库选题">
                            <el-button @click="nodeClick" class="icon-e" icon="ele-Select" text type="primary">前往选题</el-button>
                        </el-form-item>
                    </el-col>
                    <el-col v-if="ruleForm.n_SelectionMethod === 1" :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="单选题数量" prop="n_SingleChoiceNum">
                            <el-input v-model="ruleForm.n_SingleChoiceNum" type="number" placeholder="请输入单选题数量" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col v-if="ruleForm.n_SelectionMethod === 1" :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="多选题数量" prop="n_MultipleChoiceNum">
                            <el-input v-model="ruleForm.n_MultipleChoiceNum" type="number" placeholder="请输入多选题数量" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col v-if="ruleForm.n_SelectionMethod === 1" :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="判断题数量" prop="n_TrueOrFalseNum">
                            <el-input v-model="ruleForm.n_TrueOrFalseNum" type="number" placeholder="请输入判断题数量" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
                        <el-form-item label="考卷描述" prop="v_Description">
                            <el-input v-model="ruleForm.v_Description" type="textarea" placeholder="请输入考卷描述" clearable />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <el-button @click="cancelUseClick">取 消</el-button>
                <el-button v-if="ruleForm.n_SelectionMethod === 1" type="primary" :loading="repeatDis" :disabled="repeatDis" @click="submitForm(ruleFormRef)">提 交</el-button>
            </template>
        </el-dialog>
        <SelectTopic 
            :selectDialog="selectDialog" 
            :selectInfo="selectInfo" 
            :basicsInfo="basicsInfo"
            @selectUseClick="selectUseClick"
            @cancelSelectClick="cancelSelectClick"
        />
    </div>
</template>
<script lang="ts">
import { defineComponent, ref, reactive , computed , toRef , toRefs , toRaw , onMounted , watch } from 'vue'
import { FormInstance, FormRules , ElMessage, ElMessageBox } from 'element-plus'
import { OmsEduExaminationPaperAdd , OmsEduExaminationPaperUpdate , EduTrainingPlanList } from '/@/api/centerControl/sms';
import SelectTopic from './SelectTopic.vue';

/*** 定义接口基础数据类型 */
interface formType {
    repeatDis: Boolean,
    ruleForm: ruleFormType,
}
/*** form 表单数据类型 */
type ruleFormType = {
    v_CourseName: String, // 培训计划（用于显示）
    l_TrainingPlanId: Number, // 培训计划id（传给接口）
    v_Name: String, // 试卷名称
    n_Min: Number, // 考试时长
    v_PIDM: String, // 奖惩措施
    n_SelectionMethod: Number, // 选题方式（自定义0/随机1）
    n_ScopeExcellentMin: Number, // 优秀线 
    n_ScopeQualifiedMin: Number, // 合格线
    v_Description: String, // 考卷描述
    n_TrueOrFalseNum: Number, // 判断题数量
    n_SingleChoiceNum: Number, // 单选题数量
    n_MultipleChoiceNum: Number, // 多选题数量
}
export default defineComponent( {
    name: 'add-edit-ExaminationPaper',
    components: {
        SelectTopic
    },
    props: {
        isUseDialog:{
            type: Boolean,
            default: false,
        },
        repairInfo: {
            type: String,
            default: ''
        }
    },
    setup(props,ctx){
        const titleCon = ref();
        const ruleFormRef = ref();
        const selectDialog = ref(false);
        const selectInfo = ref('');
        const basicsInfo = ref('');
        const planOption = ref();

        const planChange = (val: any) => {
            state.ruleForm.v_CourseName = val.v_CourseName; // 培训计划（用于显示）
            state.ruleForm.l_TrainingPlanId = val.id; // 培训计划id（传给接口）
        }

        /*** state 引用接口定义基础数据初始值 */
        const state = reactive < formType > ({
            repeatDis: false,
            ruleForm: {} as ruleFormType
        })

        /*** 基础验证 rules */
        const rules = reactive < FormRules > ({
            /*** 放置验证 */
            // 试卷名称
            v_Name: [
				{ required: true, message: '请输入试卷名称', trigger: 'blur' },
			],
            // 考试时长
            n_Min: [
				{ required: true, message: '请输入考试时长', trigger: 'blur' },
			],
            // 优秀线分数
            n_ScopeExcellentMin: [
				{ required: true, message: '请输入优秀线分数', trigger: 'blur' },
			],
            // 合格线分数
            n_ScopeQualifiedMin: [
				{ required: true, message: '请输入合格线分数', trigger: 'blur' },
			],
            // 判断题数量
            n_TrueOrFalseNum: [
				{ required: true, message: '请输入判断题数量', trigger: 'blur' },
			],
            // 单选题数量
            n_SingleChoiceNum: [
				{ required: true, message: '请输入单选题数量', trigger: 'blur' },
			],
            // 多选题数量
            n_MultipleChoiceNum: [
				{ required: true, message: '请输入多选题数量', trigger: 'blur' },
			],
            // 试卷描述
            v_Description: [
                { required: true, message: '请输入考卷描述', trigger: 'blur' },
            ],
            // 培训计划
            v_CourseName: [
                { required: true, message: '请选择培训计划', trigger: 'change' },
            ],
        });

        /*** selectUseClick 题库选题提交事件 */
        const selectUseClick = () => {
            selectDialog.value = false;
            ctx.emit('updateData')
            ctx.emit('customClick')
        }

        /*** cancelSelectClick 题库选题取消事件 */
        const cancelSelectClick = () => {
            selectDialog.value = false;
        }

        /*** selectTopicChange 选择选题选择方式 */
        const selectTopicChange = (val:any) => {
            console.log(val,'val')
        };

        /*** handleClose 关闭按钮点击事件 */
        const handleClose = () => {
            ctx.emit('cancelUseClick')
        }

        /*** cancelUseClick 取消事件 */
        const cancelUseClick = () => {
            ctx.emit('cancelUseClick')
        }

        /*** submitForm 提交事件 */
        const submitForm = (formEl: FormInstance | undefined) => {
            if(!formEl) return
            formEl.validate( async (valid) => {
                if(valid){
                    let param = toRaw(state.ruleForm)
                    param.n_Min = Number(param.n_Min);
                    param.n_MultipleChoiceNum = Number(param.n_MultipleChoiceNum);
                    param.n_ScopeExcellentMin = Number(param.n_ScopeExcellentMin);
                    param.n_ScopeQualifiedMin = Number(param.n_ScopeQualifiedMin);
                    param.n_SingleChoiceNum = Number(param.n_SingleChoiceNum);
                    param.n_TrueOrFalseNum = Number(param.n_TrueOrFalseNum);
                    state.repeatDis = true;
                    try{
                        let res: any;
                        if(props.repairInfo !== ''){
                            res = await OmsEduExaminationPaperUpdate(param);
                        }else{
                            res = await OmsEduExaminationPaperAdd(param);
                        }
                        if(res.success){
                            state.repeatDis = false;
                            ctx.emit('updateData')
                            ctx.emit('controlUseClick')
                        }else{
                            state.repeatDis = false;
                        }
                    }catch(error){ state.repeatDis = false; }
                    
                }else{
                    console.log('error submit!')
					return false
                }
            })
        }

        /*** clean 清空数据 */
        const clean = () => {
            ruleFormRef.value.resetFields()
        }

        /*** 监听isUseDialog的变化 */
        watch(() => props.isUseDialog,(newVal) => {
            if(newVal){
                getPlanList();
                if(props.repairInfo !== ''){
                    titleCon.value = '编辑'
                    // 状态数据重置
                    state.repeatDis = false;
                    let getData = JSON.parse(props.repairInfo);
                    state.ruleForm = getData;
                }else{
                    titleCon.value = '新增';
                    state.ruleForm = {
                        v_CourseName: '', // 培训计划（用于显示）
                        l_TrainingPlanId: 0, // 培训计划id（传给接口）
                        v_Name: '', // 试卷名称
                        n_Min: 0, // 考试时长
                        v_PIDM: '', // 奖惩措施
                        n_SelectionMethod: 0, // 选题方式（自定义0/随机1）
                        n_ScopeExcellentMin: 0, // 优秀线 
                        n_ScopeQualifiedMin: 0, // 合格线
                        v_Description: '', // 考卷描述
                        n_TrueOrFalseNum: 0, // 判断题数量
                        n_SingleChoiceNum: 0, // 单选题数量
                        n_MultipleChoiceNum: 0, // 多选题数量
                    }
                }
            }
        })

        /*** getPlanList 获取培训计划列表 */
        const getPlanList = async() => {
            let param = {}
            let res:any = await EduTrainingPlanList(param);
            if(res.success) planOption.value = res.data;
        }

        /*** isUseDialog 响应弹窗的关闭  */
        const isUseDialog = computed(() => {
            return props.isUseDialog
        })

        /*** nodeClick 前往选题 */
        const nodeClick = () => {
            // 试卷名称不能为空
            if(state.ruleForm.v_Name === ''){
                ElMessage({
                    type: 'warning',
                    message: '试卷名称不能为空',
                });
                return;
            }
            // 考试时长不能为空
            if(state.ruleForm.n_Min === 0){
                ElMessage({
                    type: 'warning',
                    message: '请输入考试时长',
                });
                return;
            }
            // 优秀线不能为空
            if(state.ruleForm.n_ScopeExcellentMin === 0){
                ElMessage({
                    type: 'warning',
                    message: '请输入优秀线分数',
                });
                return;
            }
            // 合格线不能为空
            if(state.ruleForm.n_ScopeQualifiedMin === 0){
                ElMessage({
                    type: 'warning',
                    message: '请输入合格线分数',
                });
                return;
            }
            // 试卷描述不能为空
            if(state.ruleForm.v_Description === ''){
                ElMessage({
                    type: 'warning',
                    message: '请输入考卷描述',
                });
                return;
            }
            // 培训计划不能为空
            if(state.ruleForm.v_CourseName === ''){
                ElMessage({
                    type: 'warning',
                    message: '请选择培训计划',
                });
                return;
            }
            state.ruleForm.n_Min = Number(state.ruleForm.n_Min);
            state.ruleForm.n_ScopeExcellentMin = Number(state.ruleForm.n_ScopeExcellentMin);
            state.ruleForm.n_ScopeQualifiedMin = Number(state.ruleForm.n_ScopeQualifiedMin);
            basicsInfo.value = JSON.stringify(state.ruleForm);
            selectDialog.value = true;
        }

        return {
            handleClose,
            submitForm,
            cancelUseClick,
            clean,
            ruleFormRef,
            titleCon,
            ...toRefs(state),
            isUseDialog,
            rules,
            selectTopicOption: [
                {label: '自定义选题',value: 0},
                {label: '随机选题',value: 1},
            ],
            selectTopicChange,
            nodeClick,
            basicsInfo,
            selectDialog,
            selectInfo,
            selectUseClick,
            cancelSelectClick,
            planChange,
            planOption,
        }
    },
} )
</script>
<style scoped lang="scss">
    :deep(.el-select){
        width: 100%!important;
    }
    :deep(.el-input){
        width: 100%;
    }
</style>